package com.samphanie.auiu.common.filter;

import cn.hutool.core.util.StrUtil;
import com.samphanie.auiu.common.exception.ApiException;

import static com.samphanie.auiu.common.constants.AuiuConstants.SQL_PATTERN;

/**
 * SQL过滤
 *
 * @author ZSY
 * @email 1451691457@qq.com
 */
public class SQLFilter {
    /**
     * SQL注入过滤
     *
     * @param str 待验证的字符串
     */
    public static String sqlInject(String str) {

        if (StrUtil.isBlank(str)) {
            return null;
        }

        if (StrUtil.isNotEmpty(str) && !isValidOrderBySql(str)) {
            throw new ApiException("参数不符合规范，不能进行查询");
        }

        // 去掉'|"|;|\字符
        str = StrUtil.replace(str, "'", "");
        str = StrUtil.replace(str, "\"", "");
        str = StrUtil.replace(str, ";", "");
        str = StrUtil.replace(str, "\\", "");

        // 转换成小写
        str = str.toLowerCase();

        // 非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        // 判断是否包含非法字符
        for (String keyword : keywords) {
            if (str.contains(keyword)) {
                throw new ApiException("包含非法字符");
            }
        }

        return str;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value) {
        return value.matches(SQL_PATTERN);
    }
}
